<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5" type="home">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '我的任务',
  },
}
</route>
<template>
  <view class="task-page">
    <!-- 自定义导航栏 -->
    <view
      class="custom-nav-bar bg-white p-4 border-b border-gray-200 flex justify-between items-center"
      :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
    >
      <text class="text-xl font-semibold" @doubleclick="showDevMenu">我的任务</text>
      <view class="flex space-x-4">
        <view class="text-gray-500" @click="navigateToCategories">
          <text class="i-fa-solid:tag"></text>
        </view>
        <view class="text-gray-500" @click="toggleFilter">
          <text class="i-fa-solid:filter"></text>
        </view>
      </view>
    </view>

    <!-- 正在加载 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">{{ loadingState }}</text>
      
      <!-- 长时间加载时显示错误提示 -->
      <view v-if="showError" class="error-container">
        <text class="error-message">{{ errorMessage }}</text>
        <button class="retry-button" @click="manualRefresh">重试</button>
      </view>
    </view>

    <!-- 正文内容 -->
    <view v-else class="task-list-container">
      <!-- 如果没有任务 -->
      <view v-if="incompleteTasks.length === 0 && completedTasks.length === 0" class="empty-state">
        <image class="empty-image" src="/static/images/empty-task.png" mode="aspectFit"></image>
        <text class="empty-text">暂无任务</text>
        <text class="empty-subtext">点击右下角按钮添加新任务</text>
      </view>

      <!-- 有任务时显示任务列表 -->
      <block v-else>
        <!-- 未完成任务 -->
        <view class="task-section">
          <view class="section-header">
            <text class="section-title">待完成</text>
            <text class="task-count">{{ incompleteTasks.length }}</text>
          </view>
          <view v-if="incompleteTasks.length === 0" class="empty-section">
            <text class="empty-section-text">没有待完成的任务</text>
          </view>
          <view v-else class="task-list">
            <view
              v-for="task in incompleteTasks"
              :key="task.id"
              class="task-item"
              @click="goToTaskDetail(task.id)"
            >
              <view class="task-checkbox" @click.stop="toggleTaskComplete(task)">
                <view class="checkbox-inner"></view>
              </view>
              <view class="task-content">
                <view class="task-header">
                  <text class="task-title">{{ task.title }}</text>
                  <view
                    v-if="task.priority"
                    :class="[
                      'priority-tag',
                      {
                        'priority-high': task.priority === 'high',
                        'priority-medium': task.priority === 'medium',
                        'priority-low': task.priority === 'low',
                      },
                    ]"
                  ></view>
                </view>
                <view v-if="task.date || task.timeRange" class="task-meta">
                  <view v-if="task.date" class="meta-item">
                    <text class="i-fa-solid:calendar-alt meta-icon"></text>
                    <text class="meta-text">{{ task.date }}</text>
                  </view>
                  <view v-if="task.timeRange" class="meta-item">
                    <text class="i-fa-solid:clock meta-icon"></text>
                    <text class="meta-text">{{ task.timeRange }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 已完成任务 -->
        <view class="task-section">
          <view class="section-header" @click="toggleCompletedVisible">
            <text class="section-title">已完成</text>
            <text class="task-count">{{ completedTasks.length }}</text>
            <text :class="['i-fa-solid:chevron-down toggle-icon', completedVisible ? 'rotate-180' : '']"></text>
          </view>
          <view v-if="completedVisible">
            <view v-if="completedTasks.length === 0" class="empty-section">
              <text class="empty-section-text">没有已完成的任务</text>
            </view>
            <view v-else class="task-list completed-list">
              <view
                v-for="task in completedTasks"
                :key="task.id"
                class="task-item completed"
                @click="goToTaskDetail(task.id)"
              >
                <view class="task-checkbox checked" @click.stop="toggleTaskComplete(task)">
                  <text class="i-fa-solid:check checkbox-inner-checked"></text>
                </view>
                <view class="task-content">
                  <view class="task-header">
                    <text class="task-title">{{ task.title }}</text>
                  </view>
                  <view class="task-meta">
                    <view class="meta-item">
                      <text class="i-fa-solid:check-circle meta-icon"></text>
                      <text class="meta-text">{{ formatCompletedDate(task.updatedAt) }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </block>
    </view>

    <!-- 添加任务按钮 -->
    <view class="add-button" @click="createTask">
      <text class="i-fa-solid:plus text-xl text-white"></text>
    </view>

    <!-- 筛选面板 -->
    <view v-if="showFilterPanel" class="filter-panel-overlay" @click="showFilterPanel = false">
      <view class="filter-panel" @click.stop>
        <view class="filter-header">
          <text class="filter-title">筛选任务</text>
          <text class="filter-close" @click="showFilterPanel = false">
            <text class="i-fa-solid:times"></text>
          </text>
        </view>
        <view class="filter-content">
          <!-- 优先级筛选 -->
          <view class="filter-section">
            <text class="filter-section-title">按优先级</text>
            <view class="filter-options">
              <view 
                class="filter-option" 
                :class="{ active: filterOptions.priority === '' }"
                @click="filterOptions.priority = ''"
              >
                全部
              </view>
              <view 
                class="filter-option" 
                :class="{ active: filterOptions.priority === 'high' }"
                @click="filterOptions.priority = 'high'"
              >
                <view class="priority-dot bg-red-500 mr-1"></view>
                高优先级
              </view>
              <view 
                class="filter-option" 
                :class="{ active: filterOptions.priority === 'medium' }"
                @click="filterOptions.priority = 'medium'"
              >
                <view class="priority-dot bg-orange-500 mr-1"></view>
                中优先级
              </view>
              <view 
                class="filter-option" 
                :class="{ active: filterOptions.priority === 'low' }"
                @click="filterOptions.priority = 'low'"
              >
                <view class="priority-dot bg-green-500 mr-1"></view>
                低优先级
              </view>
            </view>
          </view>
          
          <!-- 日期筛选 -->
          <view class="filter-section">
            <text class="filter-section-title">按日期</text>
            <view class="filter-options">
              <view class="filter-switch-option">
                <text>有截止日期</text>
                <switch 
                  :checked="filterOptions.hasDate" 
                  @change="(e) => filterOptions.hasDate = e.detail.value"
                  color="#007aff"
                />
              </view>
              <view class="filter-switch-option">
                <text>今天任务</text>
                <switch 
                  :checked="filterOptions.today" 
                  @change="(e) => filterOptions.today = e.detail.value"
                  color="#007aff"
                />
              </view>
            </view>
          </view>
          
          <!-- 分类筛选 -->
          <view class="filter-section">
            <text class="filter-section-title">按分类</text>
            <view class="filter-options category-options">
              <view 
                class="filter-option" 
                :class="{ active: filterOptions.categoryId === '' }"
                @click="filterOptions.categoryId = ''"
              >
                全部
              </view>
              <view 
                v-for="category in categories"
                :key="category.id"
                class="filter-option category-filter" 
                :class="{ active: filterOptions.categoryId === category.id }"
                @click="filterOptions.categoryId = category.id"
              >
                <text :class="[category.icon || 'i-fa-solid:tag', 'mr-1']" :style="{ color: category.color || '#8e8e93' }"></text>
                {{ category.name }}
              </view>
            </view>
          </view>
        </view>
        <view class="filter-footer">
          <button class="filter-button reset" @click="resetFilters">重置</button>
          <button class="filter-button apply" @click="applyCurrentFilters">应用</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'TaskList',
})

import { taskService } from '@/services/task-service'
import type { Task } from '@/services/task-service'
import { showDevTools } from '@/utils/dev-tools'
import { dbService } from '@/services/database'
import type { Category } from '@/services/database'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 数据加载状态
const loading = ref(true)
// 加载状态描述
const loadingState = ref('正在加载任务列表...')
// 是否显示已完成任务
const completedVisible = ref(true)
// 未完成任务列表
const incompleteTasks = ref<Task[]>([])
// 已完成任务列表
const completedTasks = ref<Task[]>([])
// 数据库是否已准备好
const dbReady = ref(false)
// 重试计数器
const retryCount = ref(0)
// 最大重试次数
const maxRetries = 5
// 加载开始时间
const loadStartTime = ref(0)
// 是否显示错误信息
const showError = ref(false)
// 错误消息
const errorMessage = ref('')

// 筛选相关
// 是否显示筛选面板
const showFilterPanel = ref(false)
// 筛选选项
const filterOptions = ref({
  priority: '',  // 优先级筛选：'high'|'medium'|'low'|''
  hasDate: false,  // 是否有日期
  today: false,    // 今天的任务
  categoryId: ''   // 分类筛选
})
// 分类列表
const categories = ref<Category[]>([])
// 原始任务列表（未筛选）
const originalIncompleteTasks = ref<Task[]>([])

/**
 * 格式化加载时间
 */
const getLoadTimeText = (): string => {
  if (!loadStartTime.value) return '';
  const seconds = Math.floor((Date.now() - loadStartTime.value) / 1000);
  return seconds > 0 ? `(${seconds}秒)` : '';
}

/**
 * 加载分类列表
 */
const loadCategories = async () => {
  try {
    categories.value = await taskService.getTaskCategories()
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

/**
 * 加载任务列表
 */
const loadTasks = async () => {
  // 如果已经尝试了最大次数，停止重试
  if (retryCount.value >= maxRetries) {
    loading.value = false
    loadingState.value = '数据加载失败，请下拉刷新或重启应用'
    showError.value = true
    errorMessage.value = '达到最大重试次数，请稍后再试或重启应用'
    return
  }

  try {
    // 首先检查数据库是否已经初始化
    if (!dbService.isInitializedSync()) {
      loadingState.value = '等待数据库初始化...'
      console.log('数据库尚未初始化，等待初始化完成')
      
      // 延迟重试
      setTimeout(() => {
        retryCount.value++
        loadTasks()
      }, 1000 * retryCount.value)
      return
    }
    
    // 记录加载开始时间
    if (retryCount.value === 0) {
      loadStartTime.value = Date.now()
    }
    
    loading.value = true
    showError.value = false
    
    if (retryCount.value > 0) {
      loadingState.value = `正在加载任务列表...${getLoadTimeText()}(第${retryCount.value}次尝试)`
    } else {
      loadingState.value = '正在加载任务列表...'
    }

    // 定时更新加载状态文字中的时间
    const updateTimer = setInterval(() => {
      if (loading.value) {
        if (retryCount.value > 0) {
          loadingState.value = `正在加载任务列表...${getLoadTimeText()}(第${retryCount.value}次尝试)`
        } else {
          loadingState.value = `正在加载任务列表...${getLoadTimeText()}`
        }
      }
    }, 1000)

    // 获取未完成任务
    originalIncompleteTasks.value = await taskService.getIncompleteTasks()
    
    // 应用筛选条件
    applyFilters()
    
    // 获取已完成任务
    completedTasks.value = await taskService.getCompletedTasks()

    // 加载分类列表（用于筛选）
    await loadCategories()

    console.log(`加载任务成功: ${incompleteTasks.value.length} 未完成, ${completedTasks.value.length} 已完成`)
    
    // 清除定时器
    clearInterval(updateTimer)
    
    // 重置重试计数器
    retryCount.value = 0
    
    // 数据库已准备好
    dbReady.value = true
    
    // 隐藏加载状态
    loading.value = false
  } catch (error) {
    console.error('加载任务失败:', error)
    
    // 增加重试计数
    retryCount.value++
    
    // 显示错误信息
    if (retryCount.value >= 2) {
      showError.value = true
      errorMessage.value = error instanceof Error 
        ? error.message 
        : '加载任务失败，正在重试...'
    }
    
    // 根据错误类型决定重试策略
    const waitTime = error instanceof Error && error.message.includes('初始化') 
      ? 1000 * retryCount.value  // 数据库初始化问题
      : 2000 * retryCount.value  // 其他错误
      
    loadingState.value = `加载失败，${waitTime}ms后重试(${retryCount.value}/${maxRetries})...`
    
    setTimeout(() => {
      loadTasks()
    }, waitTime)
  }
}

/**
 * 应用筛选条件
 */
const applyFilters = () => {
  // 复制原始数据
  let filtered = [...originalIncompleteTasks.value]
  
  // 按优先级筛选
  if (filterOptions.value.priority) {
    filtered = filtered.filter(task => task.priority === filterOptions.value.priority)
  }
  
  // 按日期筛选
  if (filterOptions.value.hasDate) {
    filtered = filtered.filter(task => !!task.date)
  }
  
 // 今天的任务
  if (filterOptions.value.today) {
    const today = new Date().toISOString().split('T')[0]
    filtered = filtered.filter(task => task.date === today)
  }
  
  // 按分类筛选
  if (filterOptions.value.categoryId) {
    filtered = filtered.filter(task => task.categoryId === filterOptions.value.categoryId)
  }
  
  // 更新显示的任务列表
  incompleteTasks.value = filtered
}

/**
 * 切换任务完成状态
 */
const toggleTaskComplete = async (task: Task) => {
  try {
    const newStatus = !task.completed
    const success = await taskService.completeTask(task.id, newStatus)
    
    if (success) {
      // 更新本地数据，避免重新加载
      if (newStatus) {
        // 任务完成 - 从未完成移动到已完成
        incompleteTasks.value = incompleteTasks.value.filter(t => t.id !== task.id)
        
        // 更新完成时间
        task.updatedAt = new Date().toISOString()
        task.completed = true
        completedTasks.value = [task, ...completedTasks.value]
      } else {
        // 任务取消完成 - 从已完成移动到未完成
        completedTasks.value = completedTasks.value.filter(t => t.id !== task.id)
        
        // 更新时间
        task.updatedAt = new Date().toISOString()
        task.completed = false
        incompleteTasks.value = [task, ...incompleteTasks.value]
        
        // 根据优先级重新排序未完成任务
        incompleteTasks.value.sort((a, b) => {
          const priorityOrder = { high: 1, medium: 2, low: 3 }
          return priorityOrder[a.priority] - priorityOrder[b.priority]
        })
      }
      
      // 显示操作结果提示
      uni.showToast({
        title: newStatus ? '已完成任务' : '已恢复任务',
        icon: 'success',
        duration: 1500
      })
    } else {
      // 操作失败提示
      uni.showToast({
        title: '操作失败，请重试',
        icon: 'none',
        duration: 1500
      })
      
      // 失败时重新加载
      loadTasks()
    }
  } catch (error) {
    console.error('更新任务状态失败:', error)
    
    // 操作失败提示
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none',
      duration: 1500
    })
    
    // 如果状态更新失败，重新加载任务列表
    loadTasks()
  }
}

/**
 * 切换显示已完成任务
 */
const toggleCompletedVisible = () => {
  completedVisible.value = !completedVisible.value
}

/**
 * 跳转到任务详情页
 */
const goToTaskDetail = (id: string) => {
  uni.navigateTo({
    url: `/pages/task/detail?id=${id}`,
  })
}

/**
 * 创建新任务
 */
const createTask = () => {
  uni.navigateTo({
    url: '/pages/task/edit',
  })
}

/**
 * 格式化完成日期
 */
const formatCompletedDate = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diffDays = Math.floor((now.getTime() - date.getTime()) / (1000 * 60 * 60 * 24))
  
  if (diffDays === 0) {
    return '今天完成'
  } else if (diffDays === 1) {
    return '昨天完成'
  } else {
    return `${date.getMonth() + 1}月${date.getDate()}日完成`
  }
}

/**
 * 手动刷新，用于发生错误时用户主动触发刷新
 */
const manualRefresh = () => {
  // 重置状态
  retryCount.value = 0
  showError.value = false
  errorMessage.value = ''
  loadStartTime.value = Date.now()
  
  // 重新加载
  loadTasks()
  
  // 显示提示
  uni.showToast({
    title: '正在刷新...',
    icon: 'loading',
    duration: 1000
  })
}

// 页面生命周期钩子 - 每次页面显示时更新数据
onShow(() => {
  // 如果数据库已经准备好，直接加载数据
  if (dbReady.value) {
    loadTasks()
  } 
  // 第一次进入页面时
  else if (retryCount.value === 0) {
    // 先尝试调用一次
    loadTasks()
  }
})

// 下拉刷新处理
onPullDownRefresh(() => {
  // 重置重试计数
  retryCount.value = 0
  
  loadTasks().then(() => {
    uni.stopPullDownRefresh()
  })
})

// 开发工具菜单
// 长按标题显示开发工具菜单
const showDevMenu = () => {
  showDevTools()
}

// 导航到分类管理页面
const navigateToCategories = () => {
  uni.navigateTo({
    url: '/pages/task/categories',
  })
}

/**
 * 切换筛选面板显示
 */
const toggleFilter = () => {
  showFilterPanel.value = !showFilterPanel.value
}

/**
 * 重置筛选条件
 */
const resetFilters = () => {
  filterOptions.value = {
    priority: '',
    hasDate: false,
    today: false,
    categoryId: ''
  }
  applyFilters()
  showFilterPanel.value = false
}

/**
 * 应用当前筛选条件
 */
const applyCurrentFilters = () => {
  applyFilters()
  showFilterPanel.value = false
}
</script>

<style lang="scss">
.task-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f2f2f7;
}

.task-list-container {
  flex: 1;
  width: 100%;
}

.task-item {
  display: flex;
  align-items: center;
  padding: 16px;
  background-color: white;
  border-bottom: 1px solid #e5e5e5;
}

.task-checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  margin-right: 16px;
  border: 2px solid #007aff;
  border-radius: 50%;
}

.task-checkbox.checked {
  background-color: #007aff;
}

.task-priority {
  width: 12px;
  height: 12px;
  margin-right: 8px;
  border-radius: 50%;
}

.priority-high {
  background-color: #ff3b30;
}

.priority-medium {
  background-color: #ff9500;
}

.priority-low {
  background-color: #34c759;
}

.category-tag {
  padding: 4px 8px;
  margin-right: 8px;
  font-size: 12px;
  border-radius: 4px;
}

.add-button {
  position: fixed;
  right: 20px;
  bottom: 100px;
  z-index: 40;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 56px;
  height: 56px;
  color: white;
  background-color: #007aff;
  border-radius: 28px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(0, 122, 255, 0.1);
  border-top-color: #007aff;
  border-radius: 50%;
  animation: spin 1s infinite linear;
}

.loading-text {
  margin-top: 16px;
  font-size: 14px;
  color: #8e8e93;
}

/* 错误提示样式 */
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
  padding: 16px;
  background-color: rgba(255, 59, 48, 0.1);
  border-radius: 8px;
  max-width: 80%;
}

.error-message {
  font-size: 14px;
  color: #ff3b30;
  text-align: center;
  margin-bottom: 12px;
}

.retry-button {
  padding: 8px 16px;
  background-color: #007aff;
  color: white;
  border-radius: 20px;
  font-size: 14px;
  border: none;
  margin-top: 8px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.filter-panel-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 50;
  background-color: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
}

.filter-panel {
  width: 90%;
  max-height: 80%;
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.filter-header {
  padding: 16px;
  border-bottom: 1px solid #e5e5e5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-title {
  font-size: 18px;
  font-weight: 500;
}

.filter-close {
  font-size: 16px;
  color: #8e8e93;
}

.filter-content {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-section:last-child {
  margin-bottom: 0;
}

.filter-section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  margin: -4px;
}

.category-options {
  max-height: 150px;
  overflow-y: auto;
}

.filter-option {
  padding: 8px 12px;
  background-color: #f2f2f7;
  border-radius: 18px;
  margin: 4px;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.filter-option.active {
  background-color: #007aff;
  color: white;
}

.filter-option.active .priority-dot {
  background-color: white !important;
}

.category-filter.active text {
  color: white !important;
}

.priority-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 4px;
}

.filter-switch-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #f2f2f7;
  border-radius: 8px;
  margin-bottom: 8px;
  width: 100%;
}

.filter-footer {
  padding: 16px;
  border-top: 1px solid #e5e5e5;
  display: flex;
  justify-content: space-between;
}

.filter-button {
  width: 48%;
  height: 44px;
  border-radius: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}

.filter-button.reset {
  background-color: #f2f2f7;
  color: #8e8e93;
}

.filter-button.apply {
  background-color: #007aff;
  color: white;
}
</style>
